package merlin.dao;

/**
 * Singleton class providing a database connection pool.
 *
 * @author Sandip Bhattacharya
 * @version 1.0
 * modification history (who/when/what):
 * sandip	08/June/2005	created
 */

import java.sql.Connection;
import java.sql.SQLException;

import java.util.HashMap;

import javax.sql.DataSource;

import merlin.utils.ApplicationResources;

import org.apache.commons.dbcp.BasicDataSource;

public class ConnectionPool  {

	// Holds the connection pools
	private static HashMap pools = null;

	//instance data source that this ConnectionPool object points to.
	private DataSource dataSource;

	private String poolName;

	private ConnectionPool(String poolName,String driver,String url,String uid,String pwd,int maxActive){
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName(driver);
		ds.setUsername(uid);
		ds.setPassword(pwd);
		ds.setMaxActive(maxActive);
		ds.setUrl(url);

		this.poolName = poolName;
		this.dataSource = ds;
	}

	public synchronized static ConnectionPool getConnectionPool(){
		return getConnectionPool("website");
	}

	public synchronized static ConnectionPool getConnectionPool(String poolName){
		if(pools == null){
			setupConnectionPools();
		}
		return (ConnectionPool)pools.get(poolName);
	}

	public static void setupConnectionPools(){
        pools = new HashMap();
		ApplicationResources resource = ApplicationResources.getInstance();

		System.out.println(resource.getProperty("merlin.databases"));
		String[] databases = resource.getProperty("merlin.databases").split(",");
		for(int i=0;i<databases.length;i++){
			try{
				System.out.println("[ConnectionPool]Loading info for " + databases[i]);
				String driver	= resource.getProperty(databases[i] + ".database.driver");
				String url 		= resource.getProperty(databases[i] + ".database.url");
				String uid 		= resource.getProperty(databases[i] + ".database.uid");
				String pwd 		= resource.getProperty(databases[i] + ".database.password");
				int maxActive	= Integer.parseInt(resource.getProperty(databases[i] + ".database.minpoolsize"));

				pools.put(databases[i], new ConnectionPool(databases[i],driver,url,uid,pwd,maxActive));
				System.out.println("Added " + databases[i]);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}

	public synchronized Connection getConnection(){
		try{
			Connection con = dataSource.getConnection();
			return con;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public void returnConnection(Connection retCon){
		try{
			if(retCon != null && !retCon.isClosed()){
				retCon.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}